<?php


namespace api\home\controller;


use cmf\controller\RestBaseController;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\facade\Filesystem;
use think\Request;

class UploadController extends RestBaseController
{
    //本地上传
    public function uploadImage(Request $request)
    {
        //图片获取
        $image = request()->file('image');

        //本地转储
        $spic = Filesystem::disk('public')
            ->putfile('upload',$image);

        if($spic){
            $this->success('upload success',[
                'url' => $request->domain() .'/stroge/'.$spic
            ]);
        }
    }

    //七牛云上传
    public function uploadQiniu()
    {
        //接收文件
        $image = request()->file('image');
        if(!$image){
            halt('文件不存在');
        }

        // 读取对象存储配置
        $accessKey = config('app.qiniuOss.accessKey');
        $secretKey = config('app.qiniuOss.secretKey');
        $bucket = config('app.qiniuOss.bucket');

        // 鉴权
        $auth = new Auth($accessKey, $secretKey);

        // 生成上传 Token
        $token = $auth->uploadToken($bucket);

        // 构建 UploadManager 对象
        $uploadMgr = new UploadManager();

        // 要上传文件的本地路径
        $filePath = $image->getPathname();

        // 上传到存储后保存的文件名（这里使用时间戳作为文件名，严格来说这并不能保证文件名唯一，仅作为示例。）
        $saveName = time(). '.' . $image->getOriginalExtension();
        list($return, $error) = $uploadMgr->putFile($token, $saveName, $filePath);

        if ($error !== null) {
           $this->error('upload error');
        } else {
            $this->success('upload success',[
                'url' => 'http://sel3kog24.hb-bkt.clouddn.com/' . $return['key']
            ]);
        }




    }

}